package com.gzhryc.shared_device.oem.h5.agent.jetty;

import java.io.IOException;
import java.util.Date;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gzhryc.common.redis.RedisTools;
import com.gzhryc.shared_device.oem.h5.agent.LoginUserSessionManager;
import com.gzhryc.shared_device.oem.h5.agent.WebConstants;
import com.gzhryc.shared_device.oem.code.RedisDBConstants;
import com.gzhryc.shared_device.oem.h5.agent.LoginUser;
import org.apache.commons.lang3.StringUtils;

import com.gzhryc.common.PatternHelper;
import com.gzhryc.common.data.dto.AjaxResult;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import org.apache.commons.lang3.time.DateFormatUtils;

public class AjaxSecurityFilter implements Filter {

	final static Logger log = Logger.getLogger(AjaxSecurityFilter.class);

	PatternHelper patternHelper;
	PatternHelper lockPatternHelper;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		patternHelper = new PatternHelper();
		patternHelper.addExcludePattern(Pattern.compile("/agent/api/v1/login\\.do"));
		patternHelper.addExcludePattern(Pattern.compile("/agent/api/v1/resetPwd\\.do"));
		patternHelper.addExcludePattern(Pattern.compile("/agent/api/v1/sendSMS\\.do"));
		patternHelper.addExcludePattern(Pattern.compile("/agent/api/v1/wx/login\\.do"));
		patternHelper.addExcludePattern(Pattern.compile("/agent/api/v1/wx/bind\\.do"));
		patternHelper.addExcludePattern(Pattern.compile("/agent/api/v1/app/config\\.data"));

		lockPatternHelper = new PatternHelper();
		lockPatternHelper.addMatchedPatternList(Pattern.compile("^.*\\.do$"));

		lockPatternHelper.addExcludePattern(Pattern.compile("/agent/api/v1/wx/jssdk/get\\.do"));
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = HttpServletRequest.class.cast(request);
		HttpServletResponse httpResponse = HttpServletResponse.class.cast(response);

		String uri = WebUtils.getRequestURI(httpRequest);
		if (patternHelper.isExclude(uri)) {
			chain.doFilter(httpRequest, httpResponse);
			return;
		}

		String token = httpRequest.getHeader("authorization");
		if (StringUtils.isNotBlank(token)) {
			LoginUser loginUser = LoginUserSessionManager.self().getUserSession(token);
			if (loginUser != null) {
				if(lockPatternHelper.isMatched(uri,false) && !lockPatternHelper.isExclude(uri)) {
					//URL访问锁
					String key = uri + "_" + loginUser.getId();
					String date = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
					if (RedisTools.get().setnx(RedisDBConstants.URL_LOCK_DB, key, date, 3L)) {
						httpRequest.setAttribute(WebConstants.ATTR_LOGIN_USER, loginUser);
						chain.doFilter(httpRequest, httpResponse);
					} else {
						AjaxResult result = new AjaxResult(DtoConstants.FREQUENT_VISITS, "访问过于频繁");
						WebUtils.toJson(httpResponse, result);
					}
				}else {
					httpRequest.setAttribute(WebConstants.ATTR_LOGIN_USER, loginUser);
					chain.doFilter(httpRequest, httpResponse);
				}
				return;
			}
		}

		AjaxResult result = new AjaxResult(DtoConstants.LOGIN_OVERDUE, "登录过期，请重新登录");
		WebUtils.toJson(httpResponse, result);
	}

	@Override
	public void destroy() {
	}
}
